Industry 4.0 의 중심, BigData

Data Processing Based Python @ FB / jskim.kr, [김진수](bigpycraft@gmail.com)


MS Azure Cognitive Services

https://azure.microsoft.com/ko-kr/services/cognitive-services/

In [1]:
from tqdm import tqdm_notebook
In [2]:
# MS Azure Cognitive Services
bpc.Figure(bpc.AZN_FC_FIG_01)
Out[2]:
In [3]:
# 사용자 API
bpc.Figure(bpc.AZN_FC_FIG_02)
Out[3]:

Python에서 Face API 시작 자습서

필수 조건

이 자습서를 사용하려면 다음을 수행해야 합니다.

  • Python 2.7+ 또는 Python 3.5+ 중 하나를 설치합니다.
  • pip를 설치합니다.
  • 다음과 같이 Face API용 Python SDK를 설치합니다.
    bash
    pip install cognitive_face
  • Microsoft Cognitive Services에 대한 구독 키를 구합니다. 이 자습서의 주 또는 보조 키를 사용할 수 있습니다. (Face API를 사용하려면 유효한 구독 키가 있어야 합니다.)

Microsoft Azuer 사용자 API

Face

markdown
사진에서 얼굴을 감지, 식별, 분석, 구성 및 태그 지정
30,000개의 트랜잭션, 분당 20개.
엔드포인트: https://westcentralus.api.cognitive.microsoft.com/face/v1.0

키 1: 4f7ec58767f64cd391de86fbb7f8b410
키 2: 54ca95aea4784eae8aa6c1764ffdd241

이미지의 얼굴 감지

# python code

import cognitive_face as CF

KEY = '<Subscription Key>'  # Replace with a valid subscription key (keeping the quotes in place).
CF.Key.set(KEY)

BASE_URL = 'https://westus.api.cognitive.microsoft.com/face/v1.0/'  # Replace with your regional Base URL
CF.BaseUrl.set(BASE_URL)

# You can use this example JPG or replace the URL below with your own URL to a JPEG image.
img_url = 'https://raw.githubusercontent.com/Microsoft/Cognitive-Face-Windows/master/Data/detection1.jpg'
faces = CF.face.detect(img_url)
print(faces)

다음은 예제 결과입니다. 감지된 얼굴의 list입니다. 목록의 각 항목은 dict 인스턴스입니다.
여기서 faceId는 감지된 얼굴의 고유 ID이고 faceRectangle은 감지된 얼굴 위치를 설명합니다. 얼굴 ID는 24시간 후에 만료됩니다.

[실행결과]

[{u'faceId': u'68a0f8cf-9dba-4a25-afb3-f9cdf57cca51', u'faceRectangle': {u'width': 89, u'top': 66, u'height': 89, u'left': 446}}]
In [1]:
# Resource Management, Keys
# endpoint = 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0'
# subscription_key1 = '4f7ec58767f64cd391de86fbb7f8b410'
# subscription_key2 = '54ca95aea4784eae8aa6c1764ffdd241'

# base_url = endpoint
# subscription_key = subscription_key1
In [2]:
# 자신의 사용자 API를 등록
base_url = 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0'
subscription_key  = '********************************'
In [3]:
import cognitive_face as CF

KEY = subscription_key  # Replace with a valid subscription key (keeping the quotes in place).
CF.Key.set(KEY)

BASE_URL = 'https://westus.api.cognitive.microsoft.com/face/v1.0/'  # Replace with your regional Base URL
CF.BaseUrl.set(endpoint)

# You can use this example JPG or replace the URL below with your own URL to a JPEG image.
img_url = 'https://raw.githubusercontent.com/Microsoft/Cognitive-Face-Windows/master/Data/detection1.jpg'
faces = CF.face.detect(img_url)
print(faces)

얼굴 주위의 사각형 그리기

이전 명령에서 얻은 json 좌표를 사용하여 이미지에 각 얼굴을 시각적으로 나타내는 사각형을 그릴 수 있습니다.
pip install Pillow를 수행하여 PIL 이미징 모듈을 사용해야 합니다. 파일 맨 위에 다음을 추가합니다.

# python code

import requests
from io import BytesIO
from PIL import Image, ImageDraw

#Convert width height to a point in a rectangle
def getRectangle(faceDictionary):
    rect = faceDictionary['faceRectangle']
    left = rect['left']
    top = rect['top']
    bottom = left + rect['height']
    right = top + rect['width']
    return ((left, top), (bottom, right))

#Download the image from the url
response = requests.get(img_url)
img = Image.open(BytesIO(response.content))

#For each face returned use the face rectangle and draw a red box.
draw = ImageDraw.Draw(img)
for face in faces:
    draw.rectangle(getRectangle(face), outline='red')

#Display the image in the users default image browser.
img.show()
In [3]:
import requests
from io import BytesIO
from PIL import Image, ImageDraw

#Convert width height to a point in a rectangle
def getRectangle(faceDictionary):
    rect = faceDictionary['faceRectangle']
    left = rect['left']
    top = rect['top']
    bottom = left + rect['height']
    right = top + rect['width']
    return ((left, top), (bottom, right))

#Download the image from the url
response = requests.get(img_url)
img = Image.open(BytesIO(response.content))

#For each face returned use the face rectangle and draw a red box.
draw = ImageDraw.Draw(img)
for face in faces:
    draw.rectangle(getRectangle(face), outline='red')

#Display the image in the users default image browser.
img.show()
In [4]:
img
Out[4]:

추가 탐색

Face API를 추가로 탐색하는 데 도움이 되도록 이 자습서는 GUI 예제를 제공합니다.
이를 실행하려면 먼저 wxPython을 설치한 후 아래 명령을 실행합니다.

[bash]

git clone https://github.com/Microsoft/Cognitive-Face-Python.git
cd Cognitive-Face-Python
python sample

Microsoft Azuer 사용자 API

Face

markdown
Detect, identify, analyze, organize, and tag faces in photos
30,000 transactions, 20 per minute.
Endpoint: https://westcentralus.api.cognitive.microsoft.com/face/v1.0

Key 1: c7415e098dc045698a07d4171b69ba46
Key 2: 85f3e691e91c492fa9c8cc68d35773fb

AI를 통한 비즈니스 문제 해결 II

시각 : Face, 이미지의 감정 인식

  • 이미지 처리 알고리즘을 통해 사진을 스마트하게 인식, 캡션 작성, 조정
  • 분노, 경멸, 역겨움, 두려움, 행복, 중립, 슬픔, 놀람

얼굴 감성 인식 I

  • 분노, 경멸, 역겨움, 두려움, 행복, 중립, 슬픔, 놀람

AI를 통한 비즈니스 문제 해결 I

시각 : Face, 이미지의 얼굴 감지

  • 이미지 처리 알고리즘을 통해 사진을 스마트하게 인식, 캡션 작성, 조정
  • 이미지에서 얼굴부분만 탐색하여 사각형으로 시각적으로 감지

Microsoft Azuer, User API Keys

In [5]:
# 엔드포인트: https://westcentralus.api.cognitive.microsoft.com/face/v1.0
# 키 1: 4f7ec58767f64cd391de86fbb7f8b410
# 키 2: 54ca95aea4784eae8aa6c1764ffdd241

endpoint = 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0'
subscription_key1 = '4f7ec58767f64cd391de86fbb7f8b410'
subscription_key2 = '54ca95aea4784eae8aa6c1764ffdd241'

base_url = endpoint
subscription_key = subscription_key1

샘플 이미지 구글링 ^^

In [6]:
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
import requests
In [7]:
# 구글링을 통해 이미지 url 복사
image_url = 'http://harpersbazaar.co.kr/wp-content/uploads/2018/05/bazaar-2018-06-celeb-106-008.jpg'
In [8]:
face_image = requests.get(image_url)
face_image
Out[8]:
<Response [200]>
In [9]:
type(face_image)
Out[9]:
requests.models.Response
In [10]:
img = Image.open(BytesIO(face_image.content))
In [11]:
img
Out[11]:
In [12]:
import cognitive_face as CF
In [13]:
KEY = subscription_key  # Replace with a valid subscription key (keeping the quotes in place).
CF.Key.set(KEY)
In [14]:
BASE_URL = 'https://westus.api.cognitive.microsoft.com/face/v1.0/'  # Replace with your regional Base URL
CF.BaseUrl.set(endpoint)
In [15]:
faces = CF.face.detect(image_url)
faces
Out[15]:
[{'faceId': '59b2aa8d-052b-4c0b-baea-1425aff5eece',
  'faceRectangle': {'height': 363, 'left': 471, 'top': 39, 'width': 363}}]
In [16]:
draw = ImageDraw.Draw(img)
In [17]:
len(faces)
Out[17]:
1
In [18]:
face = faces[0]

rect   = face['faceRectangle']
left   = rect['left']
top    = rect['top']
width  = rect['width']
height = rect['height']
right  = left + width
bottom = top + height

print(' left, top = {l}, {t} \n bottom, right = {b}, {r} \n width, height = {w}, {h}'.format(
    l = left,
    t = top,
    b = bottom,
    r = right,
    w = width,
    h = height
))
 left, top = 471, 39 
 bottom, right = 402, 834 
 width, height = 363, 363
In [19]:
draw.rectangle(
    ((left, top), (right, bottom)),
    outline = 'red'
)
In [20]:
img
Out[20]:

MS Azure, Face API Test

In [21]:
import cognitive_face as CF
In [22]:
KEY = subscription_key  # Replace with a valid subscription key (keeping the quotes in place).
CF.Key.set(KEY)
In [23]:
BASE_URL = 'https://westus.api.cognitive.microsoft.com/face/v1.0/'  # Replace with your regional Base URL
CF.BaseUrl.set(endpoint)
In [24]:
# 효린
image_url = 'http://harpersbazaar.co.kr/wp-content/uploads/2018/05/bazaar-2018-06-celeb-106-008.jpg'

faces = CF.face.detect(image_url)
print(faces)
[{'faceId': '59b2aa8d-052b-4c0b-baea-1425aff5eece', 'faceRectangle': {'top': 39, 'left': 471, 'width': 363, 'height': 363}}]

결과값 확인

  • 서버의 응답으로 JSON 파일이 넘어오면 OK
  • JSON의 'faceRectangle' 값을 가져온후, 이미지에서 얼굴부분을 마킹해보자

얼굴 인식 마크

In [25]:
# 엔드포인트: https://westcentralus.api.cognitive.microsoft.com/face/v1.0
# 키 1: 4f7ec58767f64cd391de86fbb7f8b410
# 키 2: 54ca95aea4784eae8aa6c1764ffdd241

endpoint = 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0'
subscription_key1 = '4f7ec58767f64cd391de86fbb7f8b410'
subscription_key2 = '54ca95aea4784eae8aa6c1764ffdd241'

base_url = endpoint
subscription_key = subscription_key1
In [26]:
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
import requests
import cognitive_face as CF
In [27]:
def downloadImage(image_url):
    face_image = requests.get(image_url)
    img = Image.open(BytesIO(face_image.content))
    return img


def detectFaces(image_url):
    KEY = subscription_key  # Replace with a valid subscription key (keeping the quotes in place).
    CF.Key.set(KEY)

    BASE_URL = 'https://westus.api.cognitive.microsoft.com/face/v1.0/'  # Replace with your regional Base URL
    CF.BaseUrl.set(endpoint)
    
    faces = CF.face.detect(image_url)
    return faces


def drawFaceRectangle(faces):
    idx = 1
    
    for face in faces:
        rect = face['faceRectangle']
        left   = rect['left']
        top    = rect['top']
        width  = rect['width']
        height = rect['height']
        right  = left + width
        bottom = top + height
        
        draw.rectangle(
            ((left, top), (right, bottom)),
            outline = 'red'
        )
        
        if len(faces)>1 :
            if idx > 1:
                print('-'*50)
                
            print(' [Face {}]'.format(idx))
            
        print(' - left, top = {l}, {t} \n - bottom, right = {b}, {r} \n - width, height = {w}, {h}'.format(
            l = left,
            t = top,
            b = bottom,
            r = right,
            w = width,
            h = height
        ))
        idx += 1
        
    return img
         
In [28]:
image_url = 'http://harpersbazaar.co.kr/wp-content/uploads/2018/05/bazaar-2018-06-celeb-106-008.jpg'
In [29]:
# 이미지를 다운받은 후, 원래 이미지는 백업
img = downloadImage(image_url)
original_img = img.copy()
original_img
Out[29]:
In [30]:
faces = detectFaces(image_url)
faces
Out[30]:
[{'faceId': '59b2aa8d-052b-4c0b-baea-1425aff5eece',
  'faceRectangle': {'height': 363, 'left': 471, 'top': 39, 'width': 363}}]
In [31]:
draw = ImageDraw.Draw(img)
In [32]:
detection_img = drawFaceRectangle(faces)
 - left, top = 471, 39 
 - bottom, right = 402, 834 
 - width, height = 363, 363
In [33]:
detection_img
Out[33]:
In [34]:
faces = CF.face.detect(image_url)
print(faces)
[{'faceId': '59b2aa8d-052b-4c0b-baea-1425aff5eece', 'faceRectangle': {'top': 39, 'left': 471, 'width': 363, 'height': 363}}]
In [35]:
draw = ImageDraw.Draw(img)
draw
Out[35]:
<PIL.ImageDraw.ImageDraw at 0x19994983a58>

얼굴 인식 마크 : 2개이상의 얼굴

In [36]:
# 효린 & 소유
image_url = 'http://img.tf.co.kr/article/home/2015/09/02/201517841441157761.jpg'
In [37]:
img = downloadImage(image_url)
sistar_img = img.copy()
sistar_img
Out[37]:
In [38]:
faces = detectFaces(image_url)
draw = ImageDraw.Draw(img)
detection_img = drawFaceRectangle(faces)
 [Face 1]
 - left, top = 353, 60 
 - bottom, right = 127, 420 
 - width, height = 67, 67
--------------------------------------------------
 [Face 2]
 - left, top = 83, 55 
 - bottom, right = 117, 145 
 - width, height = 62, 62
In [39]:
detection_img
Out[39]:

얼굴 인식 마크 : N개의 얼굴

  • 얼굴 이미지가 작은 경우 인식률이 떨어진다.
  • 해상도가 떨어지는 경우도 인식률이 떨어진다.
In [40]:
# 씨스타 전부
image_url = 'http://photo.jtbc.joins.com/news/2015/05/28/20150528161815685.jpg'
image_url = 'https://img.sbs.co.kr/newimg/news/20170825/201086539_1280.jpg'
image_url = 'https://kenh14cdn.com/2017/170525musiksistar1-1495719681082.jpg'
In [41]:
img = downloadImage(image_url)
snsd_img = img.copy()
snsd_img
Out[41]:
In [42]:
faces = detectFaces(image_url)
draw = ImageDraw.Draw(img)
detection_img = drawFaceRectangle(faces)
 [Face 1]
 - left, top = 552, 264 
 - bottom, right = 492, 780 
 - width, height = 228, 228
--------------------------------------------------
 [Face 2]
 - left, top = 708, 267 
 - bottom, right = 490, 931 
 - width, height = 223, 223
--------------------------------------------------
 [Face 3]
 - left, top = 1095, 328 
 - bottom, right = 550, 1317 
 - width, height = 222, 222
--------------------------------------------------
 [Face 4]
 - left, top = 249, 262 
 - bottom, right = 479, 466 
 - width, height = 217, 217
In [43]:
detection_img
Out[43]:


The BigpyCraft find the information to design valuable society with Technology & Craft.

< The End >